#include "app_router.h"
#include "log/log.h"
#include "app_mqtt.h"
#include "app_message.h"

#define DEVICE_LIST__SIZE 10
static Device *device_list[DEVICE_LIST__SIZE];
static int device_count = 0;
//发送消息
static int router_send_msg(Device *device,char *data,int len){
    //将data转换为json格式
    Message *message=app_message_initByBinary(data,len);
    char cjson[128];
    int len=app_messsage_toJson(message,cjson,sizeof(cjson));
    //发送消息到mqtt服务器
    apt_mqtt_send(cjson,len);
    //释放消息
    app_message_free(message);
    return 0;

}
static int router_recv_callback(char *json,int len){
    //将json转换为message
    Message *message=app_message_initByJson(json);
    //查找设备
    for(int i=0;i<device_count;i++){
        if(message->conn_type==device_list[i]->conn_type){
            //将message转换为二进制
            char binary[128];
            int len=app_message_toBinary(message,binary,sizeof(binary));
            int result=app_device_recvMessage(device_list[i],binary,len);
            free(message);
            return result;
        }
    }
    log_error("device not found");
    return -1;
}
int app_router_init(){

    app_mqtt_init();
    app_mqtt_registRecvCallback(router_recv_callback);
    return 0;
}



int app_router_close(){
    //关闭客户端
    apt_mqtt_close();
    //停止关闭所有注册的设备
    for(int i=0;i<device_count;i++){
        app_device_stop(device_list[i]);
        app_device_close(device_list[i]);
    }
}

int app_router_registerDevice(Device *device){
    if(device_count>=DEVICE_LIST__SIZE){
        log_error("设备列表已满");
        return -1;
    }
    device_list[device_count++]=device;
    //给设备制定为实现发送消息的函数
    device->funs->send_msg=router_send_msg;
    //启动设备
    app_device_start(device);
    return 0;
    
}